package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 盘点管理控制器
 * @date: 2025/8/11 19:26
 * @author: ftt
 */
@RestController
@RequestMapping("check")
public class CheckController {
    
    private static final Logger log = LoggerFactory.getLogger(CheckController.class);
    
    @Autowired
    private InventoryCheckService inventoryCheckService;
    
    @Autowired
    private InventoryCheckItemService inventoryCheckItemService;
    
    @Autowired
    private InventoryRecheckService inventoryRecheckService;
    
    @Autowired
    private InventoryRecheckItemService inventoryRecheckItemService;
    
    @Autowired
    private StockService stockService;
    
    @Autowired
    private WarehouseService warehouseService;
    
    @Autowired
    private ProductService productService;
    
    // ==================== 盘点管理 ====================
    
    /**
     * 分页查询盘点单
     */
    @GetMapping("/inventory/page")
    public Page<InventoryCheck> getInventoryCheckPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String checkNo,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Page<InventoryCheck> page = new Page<>(pageNum, pageSize);
            QueryWrapper<InventoryCheck> queryWrapper = new QueryWrapper<>();
            
            if (checkNo != null && !checkNo.isEmpty()) {
                queryWrapper.like("check_no", checkNo);
            }
            if (warehouseId != null) {
                queryWrapper.eq("warehouse_id", warehouseId);
            }
            if (startDate != null && !startDate.isEmpty()) {
                queryWrapper.ge("check_date", startDate);
            }
            if (endDate != null && !endDate.isEmpty()) {
                queryWrapper.le("check_date", endDate);
            }
            
            queryWrapper.orderByDesc("create_time");
            Page<InventoryCheck> result = inventoryCheckService.page(page, queryWrapper);
            
            // 填充仓库名称
            if (result.getRecords() != null && !result.getRecords().isEmpty()) {
                for (InventoryCheck check : result.getRecords()) {
                    if (check.getWarehouseId() != null) {
                        try {
                            Warehouse warehouse = warehouseService.getById(check.getWarehouseId());
                            if (warehouse != null) {
                                check.setWarehouseName(warehouse.getName());
                            }
                        } catch (Exception e) {
                            log.warn("获取仓库信息失败: warehouseId={}", check.getWarehouseId(), e);
                        }
                    }
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("查询盘点单失败", e);
            throw new RuntimeException("查询盘点单失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建盘点单
     */
    @PostMapping("/inventory")
    public InventoryCheck createInventoryCheck(@RequestBody InventoryCheck inventoryCheck) {
        try {
            // 设置创建时间和状态
            inventoryCheck.setCreateTime(new Date());
            if (inventoryCheck.getStatus() == null) {
                inventoryCheck.setStatus(0); // 默认为草稿状态
            }
            
            // 生成盘点单号
            if (inventoryCheck.getCheckNo() == null || inventoryCheck.getCheckNo().isEmpty()) {
                inventoryCheck.setCheckNo(generateInventoryCheckNo());
            }
            
            // 保存盘点单
            inventoryCheckService.save(inventoryCheck);
            
            // 保存商品明细
            if (inventoryCheck.getItems() != null && !inventoryCheck.getItems().isEmpty()) {
                for (InventoryCheckItem item : inventoryCheck.getItems()) {
                    item.setCheckId(inventoryCheck.getId());
                    inventoryCheckItemService.save(item);
                }
            }
            
            return inventoryCheck;
        } catch (Exception e) {
            log.error("创建盘点单失败", e);
            throw new RuntimeException("创建盘点单失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新盘点单
     */
    @PutMapping("/inventory")
    public InventoryCheck updateInventoryCheck(@RequestBody InventoryCheck inventoryCheck) {
        try {
            // 更新盘点单基本信息
            inventoryCheckService.updateById(inventoryCheck);
            
            // 更新商品明细
            if (inventoryCheck.getItems() != null) {
                // 删除原有明细
                inventoryCheckItemService.remove(new QueryWrapper<InventoryCheckItem>()
                    .eq("check_id", inventoryCheck.getId()));
                
                // 保存新的明细
                for (InventoryCheckItem item : inventoryCheck.getItems()) {
                    item.setCheckId(inventoryCheck.getId());
                    inventoryCheckItemService.save(item);
                }
            }
            
            // 重新查询并返回最新的数据
            return inventoryCheckService.getById(inventoryCheck.getId());
        } catch (Exception e) {
            log.error("更新盘点单失败", e);
            throw new RuntimeException("更新盘点单失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除盘点单
     */
    @DeleteMapping("/inventory/{id}")
    public boolean deleteInventoryCheck(@PathVariable Long id) {
        try {
            // 删除盘点单明细
            inventoryCheckItemService.remove(new QueryWrapper<InventoryCheckItem>()
                    .eq("check_id", id));
            // 删除盘点单
            return inventoryCheckService.removeById(id);
        } catch (Exception e) {
            log.error("删除盘点单失败", e);
            return false;
        }
    }
    
    /**
     * 审核盘点单
     */
    @PutMapping("/inventory/audit/{id}")
    public boolean auditInventoryCheck(@PathVariable Long id) {
        try {
            // 获取盘点单详情
            InventoryCheck inventoryCheck = inventoryCheckService.getById(id);
            if (inventoryCheck == null) {
                log.error("盘点单不存在: {}", id);
                return false;
            }
            
            // 检查盘点单状态
            if (inventoryCheck.getStatus() != 0) {
                log.error("盘点单状态不正确，无法审核: id={}, status={}", id, inventoryCheck.getStatus());
                return false;
            }
            
            // 获取商品明细
            List<InventoryCheckItem> items = inventoryCheckItemService.lambdaQuery()
                    .eq(InventoryCheckItem::getCheckId, id)
                    .list();
            
            if (items == null || items.isEmpty()) {
                log.error("盘点单没有商品明细: {}", id);
                return false;
            }
            
            // 调整库存（根据盘点差异调整）
            for (InventoryCheckItem item : items) {
                java.math.BigDecimal difference = item.getActualQuantity().subtract(item.getQuantity());
                if (difference.compareTo(java.math.BigDecimal.ZERO) != 0) {
                    if (!adjustStock(item.getProductId(), inventoryCheck.getWarehouseId(), difference)) {
                        log.error("调整商品库存失败: productId={}, warehouseId={}, difference={}", 
                            item.getProductId(), inventoryCheck.getWarehouseId(), difference);
                        return false;
                    }
                }
            }
            
            // 更新盘点单状态为已审核
            inventoryCheck.setStatus(1);
            inventoryCheck.setAuditTime(new Date());
            inventoryCheckService.updateById(inventoryCheck);
            
            log.info("盘点单审核成功: {}", id);
            return true;
        } catch (Exception e) {
            log.error("审核盘点单失败: {}", id, e);
            return false;
        }
    }
    
    /**
     * 获取盘点单详情（包含明细）
     */
    @GetMapping("/inventory/withDetails/{id}")
    public InventoryCheck getInventoryCheckWithDetails(@PathVariable Long id) {
        try {
            InventoryCheck inventoryCheck = inventoryCheckService.getById(id);
            if (inventoryCheck != null) {
                // 填充仓库名称
                if (inventoryCheck.getWarehouseId() != null) {
                    try {
                        Warehouse warehouse = warehouseService.getById(inventoryCheck.getWarehouseId());
                        if (warehouse != null) {
                            inventoryCheck.setWarehouseName(warehouse.getName());
                        }
                    } catch (Exception e) {
                        log.warn("获取仓库信息失败: warehouseId={}", inventoryCheck.getWarehouseId(), e);
                    }
                }
                
                // 获取商品明细并填充商品信息
                List<InventoryCheckItem> items = inventoryCheckItemService.lambdaQuery()
                        .eq(InventoryCheckItem::getCheckId, id)
                        .list();
                
                if (items != null && !items.isEmpty()) {
                    for (InventoryCheckItem item : items) {
                        if (item.getProductId() != null) {
                            try {
                                // 获取商品信息
                                Product product = productService.getById(item.getProductId());
                                if (product != null) {
                                    item.setProductName(product.getName());
                                    item.setProductCode(product.getBarcode());
                                }
                                
                                // 获取系统库存数量
                                Stock stock = stockService.lambdaQuery()
                                        .eq(Stock::getProductId, item.getProductId())
                                        .eq(Stock::getWarehouseId, inventoryCheck.getWarehouseId())
                                        .one();
                                if (stock != null) {
                                    item.setQuantity(stock.getQuantity());
                                } else {
                                    // 如果没有库存记录，设置为0
                                    item.setQuantity(java.math.BigDecimal.ZERO);
                                }
                            } catch (Exception e) {
                                log.warn("获取商品信息或库存失败: productId={}, warehouseId={}", 
                                    item.getProductId(), inventoryCheck.getWarehouseId(), e);
                                // 设置默认值
                                item.setQuantity(java.math.BigDecimal.ZERO);
                            }
                        }
                    }
                }
                
                inventoryCheck.setItems(items);
            }
            return inventoryCheck;
        } catch (Exception e) {
            log.error("获取盘点单详情失败: {}", id, e);
            throw new RuntimeException("获取盘点单详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取商品在指定仓库的系统库存数量
     */
    @GetMapping("/inventory/stock/{productId}/{warehouseId}")
    public java.math.BigDecimal getProductStockQuantity(@PathVariable Long productId, @PathVariable Long warehouseId) {
        try {
            Stock stock = stockService.lambdaQuery()
                    .eq(Stock::getProductId, productId)
                    .eq(Stock::getWarehouseId, warehouseId)
                    .one();
            return stock != null ? stock.getQuantity() : java.math.BigDecimal.ZERO;
        } catch (Exception e) {
            log.error("获取商品库存失败: productId={}, warehouseId={}", productId, warehouseId, e);
            return java.math.BigDecimal.ZERO;
        }
    }
    
    // ==================== 盘点复盘管理 ====================
    
    /**
     * 分页查询盘点复盘单
     */
    @GetMapping("/recheck/page")
    public Page<InventoryRecheck> getInventoryRecheckPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String recheckNo,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Page<InventoryRecheck> page = new Page<>(pageNum, pageSize);
            QueryWrapper<InventoryRecheck> queryWrapper = new QueryWrapper<>();
            
            if (recheckNo != null && !recheckNo.isEmpty()) {
                queryWrapper.like("recheck_no", recheckNo);
            }
            if (warehouseId != null) {
                queryWrapper.eq("warehouse_id", warehouseId);
            }
            if (startDate != null && !startDate.isEmpty()) {
                queryWrapper.ge("recheck_date", startDate);
            }
            if (endDate != null && !endDate.isEmpty()) {
                queryWrapper.le("recheck_date", endDate);
            }
            
            queryWrapper.orderByDesc("create_time");
            Page<InventoryRecheck> result = inventoryRecheckService.page(page, queryWrapper);
            
            // 填充仓库名称
            if (result.getRecords() != null && !result.getRecords().isEmpty()) {
                for (InventoryRecheck recheck : result.getRecords()) {
                    if (recheck.getWarehouseId() != null) {
                        try {
                            Warehouse warehouse = warehouseService.getById(recheck.getWarehouseId());
                            if (warehouse != null) {
                                recheck.setWarehouseName(warehouse.getName());
                            }
                        } catch (Exception e) {
                            log.warn("获取仓库信息失败: warehouseId={}", recheck.getWarehouseId(), e);
                        }
                    }
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("查询盘点复盘单失败", e);
            throw new RuntimeException("查询盘点复盘单失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建盘点复盘单
     */
    @PostMapping("/recheck")
    public InventoryRecheck createInventoryRecheck(@RequestBody InventoryRecheck inventoryRecheck) {
        try {
            // 设置创建时间和状态
            inventoryRecheck.setCreateTime(new Date());
            if (inventoryRecheck.getStatus() == null) {
                inventoryRecheck.setStatus(0); // 默认为草稿状态
            }
            
            // 生成复盘单号
            if (inventoryRecheck.getRecheckNo() == null || inventoryRecheck.getRecheckNo().isEmpty()) {
                inventoryRecheck.setRecheckNo(generateInventoryRecheckNo());
            }
            
            // 保存复盘单
            inventoryRecheckService.save(inventoryRecheck);
            
            // 保存商品明细
            if (inventoryRecheck.getItems() != null && !inventoryRecheck.getItems().isEmpty()) {
                for (InventoryRecheckItem item : inventoryRecheck.getItems()) {
                    item.setRecheckId(inventoryRecheck.getId());
                    inventoryRecheckItemService.save(item);
                }
            }
            
            return inventoryRecheck;
        } catch (Exception e) {
            log.error("创建盘点复盘单失败", e);
            throw new RuntimeException("创建盘点复盘单失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新盘点复盘单
     */
    @PutMapping("/recheck")
    public InventoryRecheck updateInventoryRecheck(@RequestBody InventoryRecheck inventoryRecheck) {
        try {
            // 更新复盘单基本信息
            inventoryRecheckService.updateById(inventoryRecheck);
            
            // 更新商品明细
            if (inventoryRecheck.getItems() != null) {
                // 删除原有明细
                inventoryRecheckItemService.remove(new QueryWrapper<InventoryRecheckItem>()
                    .eq("recheck_id", inventoryRecheck.getId()));
                
                // 保存新的明细
                for (InventoryRecheckItem item : inventoryRecheck.getItems()) {
                    item.setRecheckId(inventoryRecheck.getId());
                    inventoryRecheckItemService.save(item);
                }
            }
            
            // 重新查询并返回最新的数据
            return inventoryRecheckService.getById(inventoryRecheck.getId());
        } catch (Exception e) {
            log.error("更新盘点复盘单失败", e);
            throw new RuntimeException("更新盘点复盘单失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除盘点复盘单
     */
    @DeleteMapping("/recheck/{id}")
    public boolean deleteInventoryRecheck(@PathVariable Long id) {
        try {
            // 删除复盘单明细
            inventoryRecheckItemService.remove(new QueryWrapper<InventoryRecheckItem>()
                    .eq("recheck_id", id));
            // 删除复盘单
            return inventoryRecheckService.removeById(id);
        } catch (Exception e) {
            log.error("删除盘点复盘单失败", e);
            return false;
        }
    }
    
    /**
     * 审核盘点复盘单
     */
    @PutMapping("/recheck/audit/{id}")
    public boolean auditInventoryRecheck(@PathVariable Long id) {
        try {
            // 获取复盘单详情
            InventoryRecheck inventoryRecheck = inventoryRecheckService.getById(id);
            if (inventoryRecheck == null) {
                log.error("盘点复盘单不存在: {}", id);
                return false;
            }
            
            // 检查复盘单状态
            if (inventoryRecheck.getStatus() != 0) {
                log.error("盘点复盘单状态不正确，无法审核: id={}, status={}", id, inventoryRecheck.getStatus());
                return false;
            }
            
            // 获取商品明细
            List<InventoryRecheckItem> items = inventoryRecheckItemService.lambdaQuery()
                    .eq(InventoryRecheckItem::getRecheckId, id)
                    .list();
            
            if (items == null || items.isEmpty()) {
                log.error("盘点复盘单没有商品明细: {}", id);
                return false;
            }
            
            // 调整库存（根据复盘差异调整）
            for (InventoryRecheckItem item : items) {
                // 安全获取数量，避免空指针异常
                java.math.BigDecimal actualQty = item.getActualQuantity();
                java.math.BigDecimal systemQty = item.getQuantity();
                
                // 如果数量为空，设置为0
                if (actualQty == null) {
                    actualQty = java.math.BigDecimal.ZERO;
                    log.warn("商品实际数量为空，设置为0: productId={}", item.getProductId());
                }
                if (systemQty == null) {
                    systemQty = java.math.BigDecimal.ZERO;
                    log.warn("商品系统数量为空，设置为0: productId={}", item.getProductId());
                }
                
                java.math.BigDecimal difference = actualQty.subtract(systemQty);
                if (difference.compareTo(java.math.BigDecimal.ZERO) != 0) {
                    if (!adjustStock(item.getProductId(), inventoryRecheck.getWarehouseId(), difference)) {
                        log.error("调整商品库存失败: productId={}, warehouseId={}, difference={}", 
                            item.getProductId(), inventoryRecheck.getWarehouseId(), difference);
                        return false;
                    }
                }
            }
            
            // 更新复盘单状态为已审核
            inventoryRecheck.setStatus(1);
            inventoryRecheck.setAuditTime(new Date());
            inventoryRecheckService.updateById(inventoryRecheck);
            
            log.info("盘点复盘单审核成功: {}", id);
            return true;
        } catch (Exception e) {
            log.error("审核盘点复盘单失败: {}", id, e);
            return false;
        }
    }
    
    /**
     * 作废盘点复盘单
     */
    @PutMapping("/recheck/void/{id}")
    public boolean voidInventoryRecheck(@PathVariable Long id) {
        try {
            // 获取复盘单详情
            InventoryRecheck inventoryRecheck = inventoryRecheckService.getById(id);
            if (inventoryRecheck == null) {
                log.error("盘点复盘单不存在: {}", id);
                return false;
            }
            
            // 检查复盘单状态
            if (inventoryRecheck.getStatus() != 0) {
                log.error("盘点复盘单状态不正确，无法作废: id={}, status={}", id, inventoryRecheck.getStatus());
                return false;
            }
            
            // 更新复盘单状态为已作废
            inventoryRecheck.setStatus(2);
            inventoryRecheck.setVoidTime(new Date());
            inventoryRecheckService.updateById(inventoryRecheck);
            
            log.info("盘点复盘单作废成功: {}", id);
            return true;
        } catch (Exception e) {
            log.error("作废盘点复盘单失败: {}", id, e);
            return false;
        }
    }
    
    /**
     * 获取盘点复盘单详情（包含明细）
     */
    @GetMapping("/recheck/withDetails/{id}")
    public InventoryRecheck getInventoryRecheckWithDetails(@PathVariable Long id) {
        try {
            InventoryRecheck inventoryRecheck = inventoryRecheckService.getById(id);
            if (inventoryRecheck != null) {
                // 填充仓库名称
                if (inventoryRecheck.getWarehouseId() != null) {
                    try {
                        Warehouse warehouse = warehouseService.getById(inventoryRecheck.getWarehouseId());
                        if (warehouse != null) {
                            inventoryRecheck.setWarehouseName(warehouse.getName());
                        }
                    } catch (Exception e) {
                        log.warn("获取仓库信息失败: warehouseId={}", inventoryRecheck.getWarehouseId(), e);
                    }
                }
                
                // 获取商品明细并填充商品信息
                List<InventoryRecheckItem> items = inventoryRecheckItemService.lambdaQuery()
                        .eq(InventoryRecheckItem::getRecheckId, id)
                        .list();
                
                if (items != null && !items.isEmpty()) {
                    for (InventoryRecheckItem item : items) {
                        if (item.getProductId() != null) {
                            try {
                                // 获取商品信息
                                Product product = productService.getById(item.getProductId());
                                if (product != null) {
                                    item.setProductName(product.getName());
                                    item.setProductCode(product.getBarcode());
                                }
                                
                                // 获取系统库存数量
                                Stock stock = stockService.lambdaQuery()
                                        .eq(Stock::getProductId, item.getProductId())
                                        .eq(Stock::getWarehouseId, inventoryRecheck.getWarehouseId())
                                        .one();
                                if (stock != null) {
                                    item.setSystemQuantity(stock.getQuantity());
                                } else {
                                    // 如果没有库存记录，设置为0
                                    item.setSystemQuantity(java.math.BigDecimal.ZERO);
                                }
                            } catch (Exception e) {
                                log.warn("获取商品信息或库存失败: productId={}, warehouseId={}", 
                                    item.getProductId(), inventoryRecheck.getWarehouseId(), e);
                                // 设置默认值
                                item.setSystemQuantity(java.math.BigDecimal.ZERO);
                            }
                        }
                    }
                }
                
                inventoryRecheck.setItems(items);
            }
            return inventoryRecheck;
        } catch (Exception e) {
            log.error("获取盘点复盘单详情失败: {}", id, e);
            throw new RuntimeException("获取盘点复盘单详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据盘点单ID获取复盘单列表
     */
    @GetMapping("/recheck/byCheckId/{checkId}")
    public List<InventoryRecheck> getRecheckByCheckId(@PathVariable Long checkId) {
        try {
            List<InventoryRecheck> rechecks = inventoryRecheckService.lambdaQuery()
                    .eq(InventoryRecheck::getCheckId, checkId)
                    .orderByDesc(InventoryRecheck::getCreateTime)
                    .list();
            
            // 填充仓库名称
            if (rechecks != null && !rechecks.isEmpty()) {
                for (InventoryRecheck recheck : rechecks) {
                    if (recheck.getWarehouseId() != null) {
                        try {
                            Warehouse warehouse = warehouseService.getById(recheck.getWarehouseId());
                            if (warehouse != null) {
                                recheck.setWarehouseName(warehouse.getName());
                            }
                        } catch (Exception e) {
                            log.warn("获取仓库信息失败: warehouseId={}", recheck.getWarehouseId(), e);
                        }
                    }
                }
            }
            
            return rechecks;
        } catch (Exception e) {
            log.error("根据盘点单ID获取复盘单失败: checkId={}", checkId, e);
            throw new RuntimeException("获取复盘单失败: " + e.getMessage());
        }
    }
    
    // ==================== 私有方法 ====================
    
    /**
     * 调整库存
     */
    private boolean adjustStock(Long productId, Long warehouseId, BigDecimal quantity) {
        try {
            // 参数验证
            if (productId == null || warehouseId == null || quantity == null) {
                log.error("调整库存参数无效: productId={}, warehouseId={}, quantity={}", productId, warehouseId, quantity);
                return false;
            }
            
            Stock stock = stockService.lambdaQuery()
                .eq(Stock::getProductId, productId)
                .eq(Stock::getWarehouseId, warehouseId)
                .one();

            if (stock != null) {
                // 安全获取库存数量，避免空指针异常
                BigDecimal currentQuantity = stock.getQuantity();
                if (currentQuantity == null) {
                    currentQuantity = BigDecimal.ZERO;
                    log.warn("库存数量为空，设置为0: productId={}, warehouseId={}", productId, warehouseId);
                }
                
                BigDecimal newQuantity = currentQuantity.add(quantity);
                if (newQuantity.compareTo(BigDecimal.ZERO) < 0) {
                    // 不允许为负，降到0
                    newQuantity = BigDecimal.ZERO;
                }
                stock.setQuantity(newQuantity);
                
                // 安全获取单价，避免空指针异常
                BigDecimal unitPrice = stock.getUnitPrice();
                if (unitPrice == null) {
                    unitPrice = BigDecimal.ZERO;
                    log.warn("库存单价为空，设置为0: productId={}, warehouseId={}", productId, warehouseId);
                }
                stock.setTotalAmount(unitPrice.multiply(newQuantity));
                stock.setUpdateTime(new Date());
                stockService.updateById(stock);
                return true;
            } else {
                // 库存不存在时，自动创建
                Stock newStock = new Stock();
                newStock.setProductId(productId);
                newStock.setWarehouseId(warehouseId);
                newStock.setQuantity(quantity.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : quantity);
                newStock.setUnitPrice(BigDecimal.ZERO); // 盘点时无法确定单价，设为0
                newStock.setTotalAmount(BigDecimal.ZERO);
                newStock.setCreateTime(new Date());
                newStock.setUpdateTime(new Date());
                stockService.save(newStock);
                log.info("自动创建库存记录: productId={}, warehouseId={}, quantity={}", productId, warehouseId, quantity);
                return true;
            }
        } catch (Exception e) {
            log.error("调整库存失败: productId={}, warehouseId={}, quantity={}", productId, warehouseId, quantity, e);
            return false;
        }
    }
    
    /**
     * 生成盘点单号
     */
    private String generateInventoryCheckNo() {
        return "PD" + System.currentTimeMillis();
    }
    
    /**
     * 生成复盘单号
     */
    private String generateInventoryRecheckNo() {
        return "FP" + System.currentTimeMillis();
    }
}
